package queue;

//环形数组队列
public class CircleArrayQueueDemo {
    public static void main(String[] args) {
        CircleArrayQueue circleArrayQueue = new CircleArrayQueue(4);
        circleArrayQueue.addQueue(1);
        circleArrayQueue.addQueue(2);
        circleArrayQueue.addQueue(3);
        circleArrayQueue.showQueue();
        circleArrayQueue.getQueue();
        System.out.println("-------");
        circleArrayQueue.showQueue();
        System.out.println("-------");
        circleArrayQueue.addQueue(4);
        circleArrayQueue.showQueue();
    }
}

class CircleArrayQueue {
    private int maxSize;//最大容量
    private int front = 0; //头 初始值0
    private int rear = 0;//尾    初始值0
    private int[] arr; // 存放数据

    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
    }

    //判断队列是否满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    //判断是否为空
    public boolean isEmpty() {
        return rear == front;
    }

    //添加数据到队列
    public void addQueue(int n) {
        //判断队列是否满
        if (isFull()) {
            System.out.println("队列满，不能加入数据~");
            return;
        }
        //直接将数据加入
        arr[rear] = n;
        //rear后移
        rear = (rear + 1) % maxSize;
    }

    //取出数据
    public int getQueue() {
        //判断队列是否为空
        if (isEmpty()) {
            throw new RuntimeException("队列为空 不能取数据");
        }
        //这里需要分许出front是指向队列的第一个元素
        //先把fromt对应的值保存到临时变量 考虑取模
        int temp = arr[front];
        //front后移
        front = (front + 1) % maxSize;
        //将临时变量返回
        return temp;
    }

    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空");
        }
        //从front开始遍历
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    //求出当前队列有效个数
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    //显示头元素
    public int headQueue() {
        if (isEmpty()) {
            System.out.println("队列开没有数据");
            throw new RuntimeException("队列开没有数据");
        }
        return arr[front];
    }
}
